package org.example.medical.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.medical.entity.User;
import org.example.medical.service.UserService;
import org.example.medical.utils.ApiResult;
import org.example.medical.utils.AuthRequired;
import org.example.medical.utils.PageResult;
import org.example.medical.utils.UserLoginRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserApiController {
    @Autowired
    private UserService userService;

    // 1. 分页查询接口
    @GetMapping
    @AuthRequired
    public ApiResult<PageResult<User>> listUsers(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String role,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        List<User> records = userService.getUsers(username, role, page, size);
        Long total = (long) records.size();
        return ApiResult.success(new PageResult<>(records, total, page, size));
    }

    // 2. 新增用户记录
    @PostMapping
    public ApiResult<?> addUser(@RequestBody User user) {
        userService.addUser(user);
        return ApiResult.success(null, "User record added successfully");
    }

    // 3. 更新用户记录
    @PutMapping("/{userId}")
    public ApiResult<?> updateUser(
            @PathVariable Integer userId,
            @RequestBody User user
    ) {
        user.setUserId(userId);
        userService.updateUser(user);
        return ApiResult.success(null, "User record updated successfully");
    }

    // 4. 软删除用户记录
    @DeleteMapping("/{userId}")
    public ApiResult<?> softDeleteUser(@PathVariable Integer userId) {
        userService.softDeleteUser(userId);
        return ApiResult.success(null, "User record deleted successfully");
    }

    // 5. 批量软删除用户记录
    @PostMapping("/batchDelete")
    public ApiResult<?> batchSoftDeleteUsers(@RequestBody List<Integer> userIds) {
        userService.batchSoftDeleteUsers(userIds);
        return ApiResult.success(null, "User records deleted successfully");
    }

    // 6. 用户注册
    @PostMapping("/register")
    public ApiResult<?> registerUser(@RequestBody User user) {
        userService.registerUser(user);
        return ApiResult.success(null, "User registered successfully");
    }

    // 7. 用户登录
    @PostMapping("/login")
    public ApiResult<?> loginUser(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request, HttpServletResponse response) {
        User user = userService.loginUser(userLoginRequest.getUsername(), userLoginRequest.getPassword());
        if (user != null) {
            // 创建 Session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            // 创建 Cookie
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(3600); // 设置 Cookie 的有效时间，单位为秒
            cookie.setPath("/"); // 设置 Cookie 的路径，使整个应用都可以访问
            response.addCookie(cookie);

            return ApiResult.success(user, "Login successful");
        } else {
            return ApiResult.failure(401, "Invalid username or password");
        }
    }
}